package com.guigu.tms.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guigu.tms.commons.dispatch.entity.OrderClassify;
import com.guigu.tms.commons.dispatch.entity.OrderClassifyOrder;
import com.guigu.tms.commons.order.entity.Order;
import com.guigu.tms.commons.order.feign.AgencyScopeFeignClient;
import com.guigu.tms.commons.order.feign.OrderFeignClient;
import com.guigu.tms.dispatch.service.IOrderClassifyOrderService;
import com.guigu.tms.dispatch.service.IOrderClassifyService;
import com.guigu.tms.dispatch.service.ITaskOrderClassifyService;
import com.guigu.tms.dispatch.utils.BaiduMapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TaskOrderClassifyServiceImpl implements ITaskOrderClassifyService {
    @Autowired(required = false)
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AgencyScopeFeignClient agencyScopeFeignClient;
    @Autowired
    private IOrderClassifyService orderClassifyService;
    @Autowired
    private IOrderClassifyOrderService orderClassifyOrderService;



    @Override
    public List<OrderClassify> execute(String agencyID, String jobId, String jobLogId) {

        //查询当前机构网点入库和中转订单
        List<Order> orders =getOrders(agencyID);

        //存放分类后的订单
        List<OrderClassify> orderClassifies=new ArrayList<>();

        //订单分类
        Map<String,List<Order>> orders1=orders.stream().collect(Collectors.groupingBy(Order::groupBy));

        //构建分类后的订单
        orders1.forEach((key,value)->{
            OrderClassify orderClassify = new OrderClassify();
            orderClassify.setId(IdWorker.getIdStr());
            orderClassify.setJobId(jobId);
            orderClassify.setJobLogId(jobLogId);
            orderClassify.setCurrentAgencyId(agencyID);
            orderClassify.setStartAgencyId(value.get(0).getStartAgencyId());
            orderClassify.setEndAgencyId(value.get(0).getEndAgencyId());
            orderClassify.setClassify(key);
            orderClassify.setTotal(value.size());
            orderClassifies.add(orderClassify);
        });
        //将订单分类保存
        Save(orderClassifies);
        return orderClassifies;
    }

    /**
     * 保存订单分类信息
     * @param orderClassifies
     */
    private void Save(List<OrderClassify> orderClassifies) {
        orderClassifies.forEach(item->{
            //如果是新订单保存分类 否则（中转订单）查询分类编号
            if(item.isNew()){
                orderClassifyService.save(item);
                item.getOrders().forEach(item1->{
                    OrderClassifyOrder orderClassifyOrder = new OrderClassifyOrder();
                    orderClassifyOrder.setId(IdWorker.getIdStr());
                    orderClassifyOrder.setOrderClassifyId(item.getId());
                    orderClassifyOrder.setOrderId(item1.getOrderId());
                    orderClassifyOrderService.save(orderClassifyOrder);
                });
            }else {
                String orderId =item.getOrders().get(0).getOrderId();
                QueryWrapper<OrderClassifyOrder> wrapper=new QueryWrapper<>();
                wrapper.eq("order_id",orderId);
                OrderClassifyOrder one = orderClassifyOrderService.getOne(wrapper);
                item.setId(one.getOrderClassifyId());
            }
        });
    }

    public List<Order> getOrders(String agencyID){
        Order order = new Order();
        order.setStatus(4);
        order.setCurrentAgencyId(agencyID);
        //获取新订单
        List<Order> orders1 = orderFeignClient.getOrdersByOrder(order);
        //获取中转订单
        order.setStatus(5);
        List<Order> orders2 = orderFeignClient.getOrdersByOrder(order);

        orders1=orders1.stream().map(item->{
            item.setStartAgencyId(agencyID);
            item.setEndAgencyId(getEndAgencyId(item));
            return item;
        }).collect(Collectors.toList());

        orders2=orders2.stream().map(item->{
            item.setStartAgencyId(getStartAgencyId(item));
            item.setEndAgencyId(getEndAgencyId(item));
            return item;
        }).collect(Collectors.toList());

        orders1.addAll(orders2);
        return orders1;
    }

    /**
     * 获取起始机构编号
     * @return
     */
    private String getStartAgencyId(Order order) {
        //获取发件人地址经纬度
        String position= BaiduMapUtils.getCoordinate(order.getSenderFullAddress());
        //根据经纬度获得起始机构编号
        return agencyScopeFeignClient.getOrderAgencyByPosition(position);
    }
    /**
     * 获取目的机构编号
     * @return
     */
    private String getEndAgencyId(Order order) {
        //获取发件人地址经纬度
        String position= BaiduMapUtils.getCoordinate(order.getReceiverFullAddress());
        //根据经纬度获得起始机构编号
        return agencyScopeFeignClient.getOrderAgencyByPosition(position);
    }

}
